# *******************************************
# Juan C. Caicedo
# jccaicedoru@bt.unal.edu.co 
# Universidad Nacional de Colombia
# 2011
# *******************************************

import os,sys

# *******************************************
# Writes a matrix to disk using sparse format.
# Standard sparse format: row col value
# ******************************************

if len(sys.argv) < 3:
  print "Convert2Sparse.py input output [transpose]"
  sys.exit()

input = open(sys.argv[1])
output = open(sys.argv[2],"w")
transpose = True if len(sys.argv) == 4 else False

i = 1
for line in input.readlines():
  values = map(float, line.split())
  norm1 = sum(values)
  for j in range(1,len(values)+1):
    k = j - 1
    if values[k] != 0.0:
      v = str(values[k]/norm1)
      r,c = (str(j), str(i)) if transpose else (str(i), str(j))
      output.write(r + " " + c + " " + v + "\n")
  i += 1

input.close()
output.close()
